package yunquan.wang.base.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import yunquan.wang.base.config.AppConfig;
import yunquan.wang.base.dao.PropertyFilter;

public abstract class WebHelper {
	private static final Logger logger = LoggerFactory
			.getLogger(WebHelper.class);
	public static final String PAGE_NO = "pageNo";
	public static final String PAGE_SIZE = "pageSize";
	public static final String ORDER_FIELD = "orderField";
	public static final String ORDER_DIRECTION = "orderDirection";
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return requestAttributes.getRequest();
	}

	public static String getRequestParam(String name) {
		return getRequest().getParameter(name);
	}
	public static String getControllerPath() {
		String path = getRequest().getAttribute("org.springframework.web.servlet.HandlerMapping.bestMatchingPattern").toString();
		path = path.substring(0, path.lastIndexOf("/"));
		return path;
	}
	
	public static <T> T fromJsonToObject(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("JsonParseException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}
	
	public static Pageable getPage() {
		PageRequest page = null;
		String orderField = getRequestParam(ORDER_FIELD);
		String orderDirection = getRequestParam(ORDER_DIRECTION);
		String pageNo = getRequestParam(PAGE_NO);
		Integer pageInt = StringUtils.isBlank(pageNo) ? 0 : Integer
				.valueOf(pageNo) - 1;
		String pageSize = getRequestParam(PAGE_SIZE);
		Integer sizeInt = StringUtils.isBlank(pageSize) ? AppConfig.getPagesize()
				: Integer.valueOf(pageSize);
		if (StringUtils.isNotBlank(orderDirection)
				&& StringUtils.isNotBlank(orderField)) {
			//
			// 多个排序
			// String[] orders= StringUtils.split(orderDirection);
			// String[] fields= StringUtils.split(orderField);
			// List<Order> orderList=new ArrayList<Order>();
			// for(int i=0;i<orders.length;i++)
			// {
			// Order order=null;
			// if(orders[i].equalsIgnoreCase("DESC"))
			// {
			// order=new Order(Direction.DESC,fields[i]);
			// }
			// else
			// {
			// order=new Order(Direction.ASC,fields[i]);
			// }
			// orderList.add(order);
			// }
			page = new PageRequest(pageInt, sizeInt, new Sort(
					Direction.fromString(orderDirection), orderField));

		} else {
			page = new PageRequest(pageInt, sizeInt);
		}
		return page;

	}
	
	public static List<PropertyFilter> filterRequest(final HttpServletRequest request) {
		List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
		//从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map<String, Object> filterParamMap = WebUtils.getParametersStartingWith(request, WebConstants.FILTER_PERFIX + "_");
 
		//分析参数Map,构造PropertyFilter列表
		for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
			String filterName = entry.getKey();
			String value = (String) entry.getValue();
			//如果value值为空,则忽略此filter.
			if (StringUtils.isNotBlank(value)) {
				PropertyFilter filter = new PropertyFilter(filterName, value);
				request.setAttribute(filterName.replace(".", "_"), value);
				filterList.add(filter);
			}
		}
		return filterList;
	}
}
